#!/bin/bash

# Prepare the program for release
# Copyright (C) 2011  Vyacheslav Levit
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

# Dependencies: w3m

PROJECT=xatk

cd "$(dirname "$0")/.."         # project root
wikidir="../wiki/"              # directory with *.wiki files

download_wiki(){
    local wikis="$(find "$wikidir" -name "*.wiki")"
    if test ! -d "doc"; then
        mkdir "doc"
    fi
    for wiki in $wikis
    do
        local nameext="${wiki##*/}"
        local name="${nameext%%.*}"
	local htmlfile="doc/$name.html"
	local textfile="doc/$name.txt"
	echo "$0: downloading $wiki..."
        scripts/googlecode-wiki2html.py "$PROJECT" "$name" "$htmlfile"
        if test $? -ne 0; then return 1; fi
	echo "$0: converting $wiki..."
	cat "$htmlfile" | w3m -dump -T text/html > "$textfile"
        if test $? -ne 0; then return 1; fi
    done
}

create_tarball(){
    local version="$(./xatk --version)"
    local dirname="$(echo "$version" | tr " " "-")"
    cp -R . ../"$dirname"
    tar -czX scripts/EXCLUDE -C .. -f ../"$dirname".tar.gz "$dirname"
    rm -R ../"$dirname"
}

usage(){
    cat << EOF

USAGE: `basename $0` [-d] [-c]

  -d -- download wiki pages from Google Code and convert them to text files
  -c -- create tar archive
EOF
}

DOWNLOAD_WIKI=0
CREATE_TARBALL=0
UPLOAD_TARBALL=0

if test $# -eq 0; then
    DOWNLOAD_WIKI=1
    CREATE_TARBALL=1
else
    while test "$1" != ""; do
        case $1 in
	    -d) DOWNLOAD_WIKI=1; shift;;
	    -c) CREATE_TARBALL=1; shift;;
	    -h|--help) usage; exit 0;;
	    *) usage; exit 1;;
	esac
    done;
fi

if test $DOWNLOAD_WIKI -eq 1; then
    download_wiki
    if test $? -ne 0; then exit 1; fi
fi
if test $CREATE_TARBALL -eq 1; then
    echo "creating tarball..."
    create_tarball
    if test $? -ne 0; then exit 1; fi
fi
